package com.czy.owner.net.http.cookie;

import com.czy.owner.net.exception.HttpTimeException;
import com.czy.owner.net.utils.CookieDbUtil;
import com.czy.owner.utils.MyLog;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * gson持久化截取保存数据
 * Created by wangyang on 2017/4/26.
 */
public class CookieInterceptor implements Interceptor {
    private CookieDbUtil dbUtil;
    /*是否缓存标识*/
    private boolean cache;
    /*url*/
    private String url;

    //     默认缓存第一页
    private String mCachePage = "1";

    public CookieInterceptor(boolean cache, String url, String mCachePage) {
        dbUtil = CookieDbUtil.getInstance();
        this.url = url;
        this.cache = cache;
        this.mCachePage = mCachePage;

    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        MyLog.e("yang", "response==" + response.toString());
        // TODO modified by King 2017/07/10:网络状态码
        if(response.code() < 200  || response.code() > 299){
            throw new HttpTimeException("网络请求:" + response.code(),true);
        }else
        if (cache) {
            ResponseBody body = response.body();
            BufferedSource source = body.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset charset = Charset.defaultCharset();
            MediaType contentType = body.contentType();
            if (contentType != null) {
                charset = contentType.charset(charset);
            }
            String bodyString = buffer.clone().readString(charset);
            CookieResulte resulte = dbUtil.queryCookieBy(url);
            MyLog.e("yang", "resulte==" + resulte);
            long time = System.currentTimeMillis();
            /*保存和更新本地数据*/
            if (resulte == null) {
                resulte = new CookieResulte(url, bodyString, time);
                dbUtil.saveCookie(resulte);
            } else {
                if (mCachePage.equals("1")) {
                    resulte.setResulte(bodyString);
                    resulte.setTime(time);
                    dbUtil.updateCookie(resulte);
                }
            }
        }
        return response;
    }
}
